package com.zhou.system.management.constant;

import com.zhou.system.management.security.model.MyUserDetails;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 用户上下文
 * <p>
 * @serial 2.0.0
 * @author 就眠儀式
 */
public class UserContext {

    /**
     * 获取当前登录用户的信息，如果未登录返回null
     *
     * @return Object 当前登录用户
     */
    public static MyUserDetails currentUser() {
        return null != getAuthentication() ? (MyUserDetails) getAuthentication().getPrincipal() : null;
    }

    /**
     * 获取当前登录用户的信息
     *
     * @return Authentication 权鉴对象
     */
    public static Authentication getAuthentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return !(authentication instanceof AnonymousAuthenticationToken) ? authentication : null;
    }

    /**
     * 验证当前用户是否登录
     *
     * @return boolean 是否登录
     */
    public static boolean isAuthentication() {
        // if security session eq s-id is not null to index
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return !(auth instanceof AnonymousAuthenticationToken);
    }

    public static SecurityContext getSecurityContext() {
        SecurityContext context = SecurityContextHolder.getContext();
        return context;
    }


}
